<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>C# Socket使用指南</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#0FC6C2',
                        accent: '#722ED1',
                        dark: '#1D2129',
                        light: '#F2F3F5'
                    },
                    fontFamily: {
                        inter: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .text-shadow {
                text-shadow: 0 2px 4px rgba(0,0,0,0.1);
            }
            .card-hover {
                transition: all 0.3s ease;
            }
            .card-hover:hover {
                transform: translateY(-5px);
                box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
            }
        }
    </style>
</head>
<body class="font-inter bg-gray-50 text-dark">
    <!-- 导航栏 -->
    <header class="sticky top-0 z-50 bg-white shadow-md">
        <nav class="container mx-auto px-4 py-3 flex justify-between items-center">
            <div class="flex items-center space-x-2">
                <i class="fa fa-wifi text-primary text-2xl"></i>
                <h1 class="text-xl md:text-2xl font-bold text-primary">C# Socket<span class="text-dark">使用指南</span></h1>
            </div>
            <div class="hidden md:flex space-x-8">
                <a href="#overview" class="text-gray-600 hover:text-primary transition-colors">概述</a>
                <a href="#properties" class="text-gray-600 hover:text-primary transition-colors">属性详解</a>
                <a href="#methods" class="text-gray-600 hover:text-primary transition-colors">方法详解</a>
                <a href="#usage" class="text-gray-600 hover:text-primary transition-colors">基本使用</a>
                <a href="#example" class="text-gray-600 hover:text-primary transition-colors">完整案例</a>
                <a href="#notes" class="text-gray-600 hover:text-primary transition-colors">注意事项</a>
            </div>
            <button class="md:hidden text-gray-600" id="mobile-menu-button">
                <i class="fa fa-bars text-xl"></i>
            </button>
        </nav>
        <!-- 移动端菜单 -->
        <div class="md:hidden hidden bg-white border-t" id="mobile-menu">
            <div class="container mx-auto px-4 py-3 flex flex-col space-y-3">
                <a href="#overview" class="text-gray-600 hover:text-primary py-2 transition-colors">概述</a>
                <a href="#properties" class="text-gray-600 hover:text-primary py-2 transition-colors">属性详解</a>
                <a href="#methods" class="text-gray-600 hover:text-primary py-2 transition-colors">方法详解</a>
                <a href="#usage" class="text-gray-600 hover:text-primary py-2 transition-colors">基本使用</a>
                <a href="#example" class="text-gray-600 hover:text-primary py-2 transition-colors">完整案例</a>
                <a href="#notes" class="text-gray-600 hover:text-primary py-2 transition-colors">注意事项</a>
            </div>
        </div>
    </header>

    <main class="container mx-auto px-4 py-8">
        <!-- 英雄区 -->
        <section class="mb-16 text-center">
            <div class="max-w-3xl mx-auto">
                <h1 class="text-[clamp(2rem,5vw,3.5rem)] font-bold mb-6 text-dark">
                    C# <span class="text-primary">Socket</span> 类使用指南
                </h1>
                <p class="text-lg md:text-xl text-gray-600 mb-8">
                    全面掌握C#中网络编程的核心知识与实践技巧
                </p>
                <div class="flex flex-wrap justify-center gap-4">
                    <a href="#properties" class="bg-primary hover:bg-primary/90 text-white px-6 py-3 rounded-lg shadow-lg transition-all flex items-center">
                        <i class="fa fa-book mr-2"></i> 开始学习
                    </a>
                    <a href="#example" class="bg-white hover:bg-gray-100 text-primary border border-primary px-6 py-3 rounded-lg shadow-lg transition-all flex items-center">
                        <i class="fa fa-code mr-2"></i> 查看案例
                    </a>
                </div>
            </div>
        </section>

        <!-- 概述部分 -->
        <section id="overview" class="mb-16 scroll-mt-20">
            <div class="bg-white rounded-xl shadow-xl p-8 card-hover">
                <h2 class="text-3xl font-bold mb-6 text-dark flex items-center">
                    <span class="bg-primary text-white p-2 rounded-lg mr-3">
                        <i class="fa fa-info-circle"></i>
                    </span>
                    一、Socket类概述
                </h2>
                <p class="text-gray-700 mb-6 text-lg">
                    在C#中，<code class="bg-light px-2 py-1 rounded text-primary font-medium">Socket</code>类是System.Net.Sockets命名空间下的一个核心类，用于实现网络通信。该类提供了一系列属性、方法和事件，使开发者能够方便地实现各种网络应用，包括客户端/服务器应用、点对点通信等。
                </p>
                <div class="bg-light rounded-lg p-6 mb-6">
                    <h3 class="text-xl font-semibold mb-4 text-dark">主要功能</h3>
                    <ul class="space-y-3">
                        <li class="flex items-start">
                            <i class="fa fa-check-circle text-green-500 mt-1 mr-3"></i>
                            <span>支持多种网络协议（TCP、UDP、IP等）</span>
                        </li>
                        <li class="flex items-start">
                            <i class="fa fa-check-circle text-green-500 mt-1 mr-3"></i>
                            <span>实现面向连接（TCP）和无连接（UDP）的通信</span>
                        </li>
                        <li class="flex items-start">
                            <i class="fa fa-check-circle text-green-500 mt-1 mr-3"></i>
                            <span>支持同步和异步通信模式</span>
                        </li>
                        <li class="flex items-start">
                            <i class="fa fa-check-circle text-green-500 mt-1 mr-3"></i>
                            <span>处理网络连接、数据传输和断开连接</span>
                        </li>
                    </ul>
                </div>
                <div class="bg-light rounded-lg p-6">
                    <h3 class="text-xl font-semibold mb-4 text-dark">典型应用场景</h3>
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                        <div class="bg-white p-4 rounded-lg shadow-sm">
                            <div class="text-primary text-2xl mb-3">
                                <i class="fa fa-server"></i>
                            </div>
                            <h4 class="font-semibold mb-2">服务器应用</h4>
                            <p class="text-gray-600">构建高性能的网络服务器</p>
                        </div>
                        <div class="bg-white p-4 rounded-lg shadow-sm">
                            <div class="text-primary text-2xl mb-3">
                                <i class="fa fa-comments"></i>
                            </div>
                            <h4 class="font-semibold mb-2">即时通讯</h4>
                            <p class="text-gray-600">开发聊天应用、消息推送系统</p>
                        </div>
                        <div class="bg-white p-4 rounded-lg shadow-sm">
                            <div class="text-primary text-2xl mb-3">
                                <i class="fa fa-gamepad"></i>
                            </div>
                            <h4 class="font-semibold mb-2">网络游戏</h4>
                            <p class="text-gray-600">实现多人在线游戏的网络通信</p>
                        </div>
                    </div>
                </div>
            </div>
        </section>

        <!-- 属性详解部分 -->
        <section id="properties" class="mb-16 scroll-mt-20">
            <div class="bg-white rounded-xl shadow-xl p-8 card-hover">
                <h2 class="text-3xl font-bold mb-6 text-dark flex items-center">
                    <span class="bg-primary text-white p-2 rounded-lg mr-3">
                        <i class="fa fa-sliders"></i>
                    </span>
                    二、常用属性及其作用
                </h2>
                
                <div class="overflow-x-auto">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gray-50">
                            <tr>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">属性</th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">作用</th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">示例</th>
                            </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-gray-200">
                            <tr>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <div class="text-sm font-medium text-dark">Available</div>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="text-sm text-gray-700">获取已经从网络接收且可供读取的数据字节数。</div>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="text-sm font-mono bg-light p-2 rounded">int availableBytes = socket.Available;</div>
                                </td>
                            </tr>
                            <tr>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <div class="text-sm font-medium text-dark">Connected</div>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="text-sm text-gray-700">获取一个值，该值指示Socket是否已连接到远程主机。</div>
                                    <div class="text-xs text-gray-500 mt-1">注意：此属性反映的是最近一次操作的连接状态，若要确认当前连接状态，需尝试发送数据。</div>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="text-sm font-mono bg-light p-2 rounded">bool isConnected = socket.Connected;</div>
                                </td>
                            </tr>
                            <tr>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <div class="text-sm font-medium text-dark">LocalEndPoint</div>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="text-sm text-gray-700">获取本地终结点。</div>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="text-sm font-mono bg-light p-2 rounded">EndPoint localEP = socket.LocalEndPoint;</div>
                                </td>
                            </tr>
                            <tr>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <div class="text-sm font-medium text-dark">RemoteEndPoint</div>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="text-sm text-gray-700">获取远程终结点。</div>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="text-sm font-mono bg-light p-2 rounded">EndPoint remoteEP = socket.RemoteEndPoint;</div>
                                </td>
                            </tr>
                            <tr>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <div class="text-sm font-medium text-dark">ReceiveBufferSize</div>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="text-sm text-gray-700">获取或设置接收缓冲区的大小。</div>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="text-sm font-mono bg-light p-2 rounded">socket.ReceiveBufferSize = 8192;</div>
                                </td>
                            </tr>
                            <tr>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <div class="text-sm font-medium text-dark">SendBufferSize</div>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="text-sm text-gray-700">获取或设置发送缓冲区的大小。</div>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="text-sm font-mono bg-light p-2 rounded">socket.SendBufferSize = 8192;</div>
                                </td>
                            </tr>
                            <tr>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <div class="text-sm font-medium text-dark">ReceiveTimeout</div>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="text-sm text-gray-700">获取或设置一个值（以毫秒为单位），该值指定调用Receive方法时Socket将等待的时间量。</div>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="text-sm font-mono bg-light p-2 rounded">socket.ReceiveTimeout = 5000;</div>
                                </td>
                            </tr>
                            <tr>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <div class="text-sm font-medium text-dark">SendTimeout</div>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="text-sm text-gray-700">获取或设置一个值（以毫秒为单位），该值指定调用Send方法时Socket将等待的时间量。</div>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="text-sm font-mono bg-light p-2 rounded">socket.SendTimeout = 5000;</div>
                                </td>
                            </tr>
                            <tr>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <div class="text-sm font-medium text-dark">Blocking</div>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="text-sm text-gray-700">获取或设置一个值，该值指示Socket是否处于阻塞模式。</div>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="text-sm font-mono bg-light p-2 rounded">socket.Blocking = false;</div>
                                </td>
                            </tr>
                            <tr>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <div class="text-sm font-medium text-dark">ProtocolType</div>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="text-sm text-gray-700">获取Socket的协议类型。</div>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="text-sm font-mono bg-light p-2 rounded">ProtocolType protocol = socket.ProtocolType;</div>
                                </td>
                            </tr>
                            <tr>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <div class="text-sm font-medium text-dark">SocketType</div>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="text-sm text-gray-700">获取Socket的类型。</div>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="text-sm font-mono bg-light p-2 rounded">SocketType socketType = socket.SocketType;</div>
                                </td>
                            </tr>
                            <tr>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <div class="text-sm font-medium text-dark">LingerState</div>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="text-sm text-gray-700">获取或设置有关Socket关闭行为的LingerOption。</div>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="text-sm font-mono bg-light p-2 rounded">
                                        LingerOption lingerOption = new LingerOption(true, 10);<br>
                                        socket.LingerState = lingerOption;
                                    </div>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </section>

        <!-- 方法详解部分 -->
        <section id="methods" class="mb-16 scroll-mt-20">
            <div class="bg-white rounded-xl shadow-xl p-8 card-hover">
                <h2 class="text-3xl font-bold mb-6 text-dark flex items-center">
                    <span class="bg-secondary text-white p-2 rounded-lg mr-3">
                        <i class="fa fa-cogs"></i>
                    </span>
                    三、常用方法及其作用
                </h2>
                
                <div class="overflow-x-auto">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gray-50">
                            <tr>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">方法</th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">作用</th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">示例</th>
                            </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-gray-200">
                            <tr>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <div class="text-sm font-medium text-dark">Connect(EndPoint remoteEP)</div>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="text-sm text-gray-700">将Socket连接到远程终结点。</div>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="text-sm font-mono bg-light p-2 rounded">
                                        socket.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8080));
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <div class="text-sm font-medium text-dark">Bind(EndPoint localEP)</div>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="text-sm text-gray-700">将Socket绑定到一个本地终结点。</div>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="text-sm font-mono bg-light p-2 rounded">
                                        socket.Bind(new IPEndPoint(IPAddress.Any, 8080));
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <div class="text-sm font-medium text-dark">Listen(int backlog)</div>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="text-sm text-gray-700">将Socket置于侦听状态。</div>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="text-sm font-mono bg-light p-2 rounded">socket.Listen(10);</div>
                                </td>
                            </tr>
                            <tr>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <div class="text-sm font-medium text-dark">Accept()</div>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="text-sm text-gray-700">接受传入的连接请求。</div>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="text-sm font-mono bg-light p-2 rounded">Socket clientSocket = socket.Accept();</div>
                                </td>
                            </tr>
                            <tr>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <div class="text-sm font-medium text-dark">Send(byte[] buffer)</div>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="text-sm text-gray-700">将数据发送到连接的Socket。</div>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="text-sm font-mono bg-light p-2 rounded">
                                        byte[] data = Encoding.UTF8.GetBytes("Hello, World!");<br>
                                        int bytesSent = socket.Send(data);
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <div class="text-sm font-medium text-dark">Receive(byte[] buffer)</div>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="text-sm text-gray-700">从绑定的Socket接收数据。</div>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="text-sm font-mono bg-light p-2 rounded">
                                        byte[] buffer = new byte[1024];<br>
                                        int bytesReceived = socket.Receive(buffer);
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <div class="text-sm font-medium text-dark">Close()</div>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="text-sm text-gray-700">关闭Socket连接并释放所有关联的资源。</div>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="text-sm font-mono bg-light p-2 rounded">socket.Close();</div>
                                </td>
                            </tr>
                            <tr>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <div class="text-sm font-medium text-dark">BeginConnect(EndPoint remoteEP, AsyncCallback callback, object state)</div>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="text-sm text-gray-700">开始一个对远程主机连接的异步请求。</div>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="text-sm font-mono bg-light p-2 rounded">
                                        socket.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), socket);
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <div class="text-sm font-medium text-dark">EndConnect(IAsyncResult asyncResult)</div>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="text-sm text-gray-700">结束一个对远程主机连接的异步请求。</div>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="text-sm font-mono bg-light p-2 rounded">
                                        socket.EndConnect(asyncResult);
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <div class="text-sm font-medium text-dark">BeginSend(byte[] buffer, int offset, int size, SocketFlags socketFlags, AsyncCallback callback, object state)</div>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="text-sm text-gray-700">开始一个向连接的Socket异步发送数据的请求。</div>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="text-sm font-mono bg-light p-2 rounded">
                                        socket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(SendCallback), socket);
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <div class="text-sm font-medium text-dark">EndSend(IAsyncResult asyncResult)</div>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="text-sm text-gray-700">结束一个向连接的Socket异步发送数据的请求。</div>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="text-sm font-mono bg-light p-2 rounded">
                                        int bytesSent = socket.EndSend(asyncResult);
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <div class="text-sm font-medium text-dark">BeginReceive(byte[] buffer, int offset, int size, SocketFlags socketFlags, AsyncCallback callback, object state)</div>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="text-sm text-gray-700">开始一个从绑定的Socket异步接收数据的请求。</div>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="text-sm font-mono bg-light p-2 rounded">
                                        socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), socket);
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <div class="text-sm font-medium text-dark">EndReceive(IAsyncResult asyncResult)</div>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="text-sm text-gray-700">结束一个从绑定的Socket异步接收数据的请求。</div>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="text-sm font-mono bg-light p-2 rounded">
                                        int bytesReceived = socket.EndReceive(asyncResult);
                                    </div>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </section>

        <!-- 基本使用部分 -->
        <section id="usage" class="mb-16 scroll-mt-20">
            <div class="bg-white rounded-xl shadow-xl p-8 card-hover">
                <h2 class="text-3xl font-bold mb-6 text-dark flex items-center">
                    <span class="bg-primary text-white p-2 rounded-lg mr-3">
                        <i class="fa fa-code"></i>
                    </span>
                    四、基本使用流程
                </h2>
                
                <div class="space-y-8">
                    <!-- 引入命名空间 -->
                    <div class="bg-light rounded-lg p-6">
                        <h3 class="text-xl font-semibold mb-4 text-dark">1. 引入命名空间</h3>
                        <pre class="bg-dark text-white p-4 rounded-lg overflow-x-auto font-mono text-sm"><code>using System.Net;
using System.Net.Sockets;
using System.Text;</code></pre>
                    </div>
                    
                    <!-- 创建TCP服务器 -->
                    <div class="bg-light rounded-lg p-6">
                        <h3 class="text-xl font-semibold mb-4 text-dark">2. 创建TCP服务器</h3>
                        <pre class="bg-dark text-white p-4 rounded-lg overflow-x-auto font-mono text-sm"><code>// 创建一个TcpListener实例
TcpListener server = new TcpListener(IPAddress.Any, 8080);

// 启动服务器
server.Start();
Console.WriteLine("服务器已启动，等待客户端连接...");

// 接受客户端连接
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("客户端已连接");

// 获取网络流
NetworkStream stream = client.GetStream();

// 读取客户端发送的数据
byte[] buffer = new byte[1024];
int bytesRead = stream.Read(buffer, 0, buffer.Length);
string data = Encoding.UTF8.GetString(buffer, 0, bytesRead);
Console.WriteLine("收到客户端消息: " + data);

// 发送响应给客户端
string response = "服务器已收到消息: " + data;
byte[] responseData = Encoding.UTF8.GetBytes(response);
stream.Write(responseData, 0, responseData.Length);

// 关闭连接
stream.Close();
client.Close();
server.Stop();</code></pre>
                    </div>
                    
                    <!-- 创建TCP客户端 -->
                    <div class="bg-light rounded-lg p-6">
                        <h3 class="text-xl font-semibold mb-4 text-dark">3. 创建TCP客户端</h3>
                        <pre class="bg-dark text-white p-4 rounded-lg overflow-x-auto font-mono text-sm"><code>// 创建一个TcpClient实例
TcpClient client = new TcpClient();

// 连接到服务器
client.Connect("127.0.0.1", 8080);
Console.WriteLine("已连接到服务器");

// 获取网络流
NetworkStream stream = client.GetStream();

// 发送数据到服务器
string message = "Hello, Server!";
byte[] data = Encoding.UTF8.GetBytes(message);
stream.Write(data, 0, data.Length);

// 读取服务器响应
byte[] buffer = new byte[1024];
int bytesRead = stream.Read(buffer, 0, buffer.Length);
string response = Encoding.UTF8.GetString(buffer, 0, bytesRead);
Console.WriteLine("收到服务器响应: " + response);

// 关闭连接
stream.Close();
client.Close();</code></pre>
                    </div>
                    
                    <!-- 创建UDP服务器 -->
                    <div class="bg-light rounded-lg p-6">
                        <h3 class="text-xl font-semibold mb-4 text-dark">4. 创建UDP服务器</h3>
                        <pre class="bg-dark text-white p-4 rounded-lg overflow-x-auto font-mono text-sm"><code>// 创建一个UdpClient实例
UdpClient server = new UdpClient(8080);
IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);

Console.WriteLine("UDP服务器已启动，等待数据...");

// 接收数据
byte[] receiveBytes = server.Receive(ref remoteEndPoint);
string receiveMessage = Encoding.UTF8.GetString(receiveBytes);
Console.WriteLine("收到来自 {0} 的消息: {1}", remoteEndPoint.ToString(), receiveMessage);

// 发送响应
string sendMessage = "UDP服务器已收到消息: " + receiveMessage;
byte[] sendBytes = Encoding.UTF8.GetBytes(sendMessage);
server.Send(sendBytes, sendBytes.Length, remoteEndPoint);

// 关闭连接
server.Close();</code></pre>
                    </div>
                    
                    <!-- 创建UDP客户端 -->
                    <div class="bg-light rounded-lg p-6">
                        <h3 class="text-xl font-semibold mb-4 text-dark">5. 创建UDP客户端</h3>
                        <pre class="bg-dark text-white p-4 rounded-lg overflow-x-auto font-mono text-sm"><code>// 创建一个UdpClient实例
UdpClient client = new UdpClient();

// 设置服务器端点
IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8080);

// 发送数据
string sendMessage = "Hello, UDP Server!";
byte[] sendBytes = Encoding.UTF8.GetBytes(sendMessage);
client.Send(sendBytes, sendBytes.Length, serverEndPoint);

// 接收响应
IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
byte[] receiveBytes = client.Receive(ref remoteEndPoint);
string receiveMessage = Encoding.UTF8.GetString(receiveBytes);
Console.WriteLine("收到来自服务器的响应: " + receiveMessage);

// 关闭连接
client.Close();</code></pre>
                    </div>
                </div>
            </div>
        </section>

        <!-- 完整案例部分 -->
        <section id="example" class="mb-16 scroll-mt-20">
            <div class="bg-white rounded-xl shadow-xl p-8 card-hover">
                <h2 class="text-3xl font-bold mb-6 text-dark flex items-center">
                    <span class="bg-primary text-white p-2 rounded-lg mr-3">
                        <i class="fa fa-project-diagram"></i>
                    </span>
                    五、完整案例：C# Socket实现简单聊天程序
                </h2>
                
                <div class="bg-light rounded-lg p-6 mb-8">
                    <h3 class="text-xl font-semibold mb-4 text-dark">案例需求</h3>
                    <p class="text-gray-700 mb-4">
                        使用C# Socket类实现一个简单的控制台聊天程序，包括服务端和客户端两部分：
                    </p>
                    <ul class="space-y-2 ml-6 list-disc text-gray-700">
                        <li>服务端可以接受多个客户端连接。</li>
                        <li>客户端可以连接到服务端并发送消息。</li>
                        <li>服务端接收消息后转发给所有连接的客户端。</li>
                        <li>实现基本的错误处理和断开连接处理。</li>
                    </ul>
                </div>
                
                <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
                    <!-- 服务端代码 -->
                    <div class="bg-light rounded-lg p-6">
                        <h3 class="text-xl font-semibold mb-4 text-dark">服务端代码</h3>
                        <pre class="bg-dark text-white p-4 rounded-lg overflow-x-auto font-mono text-sm"><code>using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace ChatServer
{
    class Program
    {
        // 存储所有客户端连接的列表
        private static List&lt;Socket&gt; clients = new List&lt;Socket&gt;();
        private static object clientsLock = new object();

        static void Main(string[] args)
        {
            try
            {
                // 创建TCP/IP套接字
                Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                
                // 绑定IP地址和端口
                IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 8888);
                serverSocket.Bind(localEndPoint);
                
                // 开始监听，最大连接数为10
                serverSocket.Listen(10);
                Console.WriteLine("服务器已启动，等待客户端连接...");
                
                // 开始接受客户端连接
                Thread acceptThread = new Thread(() => AcceptClients(serverSocket));
                acceptThread.IsBackground = true;
                acceptThread.Start();
                
                // 等待退出命令
                Console.WriteLine("输入 'exit' 退出服务器");
                while (Console.ReadLine().ToLower() != "exit") ;
                
                // 关闭所有客户端连接
                lock (clientsLock)
                {
                    foreach (Socket client in clients)
                    {
                        try { client.Close(); } catch { }
                    }
                    clients.Clear();
                }
                
                // 关闭服务器
                serverSocket.Close();
                Console.WriteLine("服务器已关闭");
            }
            catch (Exception ex)
            {
                Console.WriteLine("服务器发生错误: " + ex.Message);
            }
        }

        // 接受客户端连接的方法
        private static void AcceptClients(Socket serverSocket)
        {
            while (true)
            {
                try
                {
                    // 接受客户端连接
                    Socket clientSocket = serverSocket.Accept();
                    Console.WriteLine("客户端 {0} 已连接", clientSocket.RemoteEndPoint);
                    
                    // 添加到客户端列表
                    lock (clientsLock)
                    {
                        clients.Add(clientSocket);
                    }
                    
                    // 为每个客户端创建一个线程处理消息
                    Thread clientThread = new Thread(() => HandleClient(clientSocket));
                    clientThread.IsBackground = true;
                    clientThread.Start();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("接受客户端连接时发生错误: " + ex.Message);
                    break;
                }
            }
        }

        // 处理客户端消息的方法
        private static void HandleClient(Socket clientSocket)
        {
            try
            {
                byte[] buffer = new byte[1024];
                
                while (true)
                {
                    // 接收客户端消息
                    int bytesRead = clientSocket.Receive(buffer);
                    
                    if (bytesRead == 0) // 客户端断开连接
                    {
                        break;
                    }
                    
                    // 转换消息
                    string message = Encoding.UTF8.GetString(buffer, 0, bytesRead);
                    Console.WriteLine("来自 {0} 的消息: {1}", clientSocket.RemoteEndPoint, message);
                    
                    // 转发消息给所有客户端
                    BroadcastMessage(clientSocket, message);
                }
            }
            catch (SocketException)
            {
                // 客户端断开连接
            }
            catch (Exception ex)
            {
                Console.WriteLine("处理客户端消息时发生错误: " + ex.Message);
            }
            finally
            {
                // 从客户端列表中移除
                lock (clientsLock)
                {
                    clients.Remove(clientSocket);
                }
                
                // 关闭客户端连接
                try { clientSocket.Close(); } catch { }
                
                Console.WriteLine("客户端 {0} 已断开连接", clientSocket.RemoteEndPoint);
            }
        }

        // 广播消息给所有客户端
        private static void BroadcastMessage(Socket sender, string message)
        {
            byte[] data = Encoding.UTF8.GetBytes(string.Format("[{0}]: {1}", sender.RemoteEndPoint, message));
            
            lock (clientsLock)
            {
                foreach (Socket client in clients)
                {
                    if (client != sender && client.Connected)
                    {
                        try
                        {
                            client.Send(data);
                        }
                        catch
                        {
                            // 发送失败，可能客户端已断开
                        }
                    }
                }
            }
        }
    }
}</code></pre>
                    </div>
                    
                    <!-- 客户端代码 -->
                    <div class="bg-light rounded-lg p-6">
                        <h3 class="text-xl font-semibold mb-4 text-dark">客户端代码</h3>
                        <pre class="bg-dark text-white p-4 rounded-lg overflow-x-auto font-mono text-sm"><code>
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace ChatClient
{
    class Program
    {
        private static Socket clientSocket;
        private static volatile bool isRunning = true; // 使用volatile确保线程可见性

        static void Main(string[] args)
        {
            try
            {
                // 创建TCP/IP套接字
                clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                // 连接到服务器
                IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8888);
                clientSocket.Connect(serverEndPoint);
                Console.WriteLine("已连接到服务器 {0}", serverEndPoint);

                // 启动接收消息的线程
                Thread receiveThread = new Thread(ReceiveMessages);
                receiveThread.IsBackground = true;
                receiveThread.Start();

                // 读取用户输入并发送消息
                Console.WriteLine("输入消息并按Enter发送，输入 'exit' 退出");
                while (isRunning)
                {
                    string message = Console.ReadLine();

                    if (message.ToLower() == "exit")
                    {
                        isRunning = false;
                        break;
                    }

                    if (!string.IsNullOrEmpty(message))
                    {
                        try
                        {
                            // 发送消息时添加长度前缀
                            byte[] data = Encoding.UTF8.GetBytes(message);
                            short len = (short)data.Length;
                            byte[] lenBytes = BitConverter.GetBytes(len);
                            
                            // 确保网络字节序（大端序）
                            if (BitConverter.IsLittleEndian)
                                Array.Reverse(lenBytes);
                            
                            // 先发送长度，再发送数据
                            clientSocket.Send(lenBytes);
                            clientSocket.Send(data);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("发送消息时发生错误: " + ex.Message);
                            isRunning = false;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("客户端发生错误: " + ex.Message);
            }
            finally
            {
                // 关闭客户端连接
                isRunning = false; // 确保接收线程也退出
                if (clientSocket != null && clientSocket.Connected)
                {
                    clientSocket.Shutdown(SocketShutdown.Both); // 优雅关闭
                    clientSocket.Close();
                }

                Console.WriteLine("已断开与服务器的连接");
            }
        }

        private static void ReceiveMessages()
        {
            byte[] buffer = new byte[1024];
            
            try
            {
                while (isRunning)
                {
                    // 先接收消息长度
                    byte[] lenBytes = new byte[2];
                    int bytesRead = clientSocket.Receive(lenBytes, 0, 2, SocketFlags.None);
                    
                    if (bytesRead <= 0) // 连接关闭
                    {
                        Console.WriteLine("服务器已断开连接");
                        isRunning = false;
                        break;
                    }
                    
                    // 转换为网络字节序（大端序）
                    if (BitConverter.IsLittleEndian)
                        Array.Reverse(lenBytes);
                    
                    short messageLength = BitConverter.ToInt16(lenBytes, 0);
                    
                    // 接收消息内容
                    byte[] messageBytes = new byte[messageLength];
                    int totalBytesRead = 0;
                    
                    while (totalBytesRead < messageLength)
                    {
                        bytesRead = clientSocket.Receive(messageBytes, totalBytesRead, 
                            messageLength - totalBytesRead, SocketFlags.None);
                        
                        if (bytesRead <= 0) // 连接关闭
                        {
                            Console.WriteLine("服务器已断开连接");
                            isRunning = false;
                            break;
                        }
                        
                        totalBytesRead += bytesRead;
                    }
                    
                    if (isRunning)
                    {
                        // 转换为字符串并显示
                        string message = Encoding.UTF8.GetString(messageBytes);
                        Console.WriteLine("收到消息: " + message);
                    }
                }
            }
            catch (SocketException ex)
            {
                if (isRunning) // 仅在运行时显示错误
                    Console.WriteLine("接收消息时发生错误: " + ex.SocketErrorCode);
            }
            catch (Exception ex)
            {
                if (isRunning) // 仅在运行时显示错误
                    Console.WriteLine("接收消息时发生未知错误: " + ex.Message);
            }
            finally
            {
                isRunning = false; // 确保主线程也退出
            }
        }
    }
}    